using BuildingBlocks.Application.Messaging;
using BuildingBlocks.Domain;
using Catalog.Api.Data;
using Catalog.Api.Models;
using MongoDB.Driver;

namespace Catalog.Api.Features.CatalogItems.GetItems;  
  
public sealed record GetCatalogItemsQuery : IQuery<IReadOnlyCollection<CatalogItemResponse>>;  
  
internal sealed class GetCatalogItemsQueryHandler(CatalogDbContext context)  
    : IQueryHandler<GetCatalogItemsQuery, IReadOnlyCollection<CatalogItemResponse>>  
{  
    public async ValueTask<Result<IReadOnlyCollection<CatalogItemResponse>>> Handle(  
        GetCatalogItemsQuery request,  
        CancellationToken cancellationToken)  
    {  
        var items = await context.CatalogItems  
            .Find(Builders<CatalogItem>.Filter.Empty)  
            .SortBy(item => item.Name)  
            .ToListAsync(cancellationToken);  
  
        var responses = items.Select(Mapper.ToResponse).ToArray();  
        return Result.Success<IReadOnlyCollection<CatalogItemResponse>>(responses);  
    }  
}
